function hfile = aft_Save(hfile)
% AnyFileType::Save  - saves any BVQXfile object back to disk
%
% FORMAT:       object.Save;
%
% No input / output fields.
%
% TYPES: ALL

% Version:  v0.8a
% Build:    9102122
% Date:     OCt-21 2009, 10:10 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% only valid for single file
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, true)
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end

% get super-struct
sc = bvqxfile_getscont(hfile.L);

% check filename
if isempty(sc.F)
    error( ...
        'BVQXfile:BadFilename', ...
        'File not yet saved. Use SaveAs method instead.' ...
    );
end

% what to do
try
    switch (lower(sc.S.FFTYPE))
        case {'bff'}
            sc.C = bffio(sc.F, sc.S, sc.C);
        case {'tff'}
            [sc.C, sc.F] = tffio(sc.F, sc.S, sc.C);
        otherwise
            error( ...
                'BVQXfile:InvalidFileType', ...
                'Type not recognized (?FF): %s.', ...
                sc.S.FFTYPE ...
            );
    end
catch
    error( ...
        'BVQXfile:ErrorSavingFile', ...
        'Error saving file %s: %s.', ...
        sc.F, lasterr ...
    );
end

% set possibly changed content back
bvqxfile_setscont(hfile.L, sc);
